package java8.stream;

import java.time.Duration;
import java.time.Instant;
import java.util.stream.LongStream;

/**
 * 并行流
 */
public class Stream4 {

    public static void main(String[] args) {
        // 计算一到二十亿累加
        caculate1();
        caculate2();
        caculate3();
    }

    public static void caculate1() {
        Instant start = Instant.now();

        long sum = LongStream.rangeClosed(1, 2000000000L)
                .parallel()
                .reduce(0, Long::sum);

        Instant end = Instant.now();
        System.out.println("并行流花费时间：" + Duration.between(start, end).toMillis() + "毫秒");
    }

    public static void caculate2() {
        Instant start = Instant.now();

        long sum = LongStream.rangeClosed(1, 2000000000L)
                .reduce(0, Long::sum);


        Instant end = Instant.now();
        System.out.println("顺序流花费时间：" + Duration.between(start, end).toMillis() + "毫秒");
    }

    public static void caculate3() {
        Instant start = Instant.now();

        long sum = 0;
        for (int i = 1; i <= 2000000000L; i++) {
            sum += i;
        }

        Instant end = Instant.now();
        System.out.println("普通for循环花费时间：" + Duration.between(start, end).toMillis() + "毫秒");
    }

}